package com.dong.web.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import com.dong.web.annotation.Transaction;
import com.dong.web.database.Connected;
import com.dong.web.database.JdbcHandler;

public class ProxyHandler implements InvocationHandler {

	private Object instance;

	public Object invoke(Object proxy, final Method method, final Object[] args)
			throws Throwable {
		Class<?> clazz = instance.getClass();
		clazz.getMethod(method.getName(), method.getParameterTypes());
		Method annotationMethod = clazz.getMethod(method.getName(),
				method.getParameterTypes());
		if (annotationMethod.isAnnotationPresent(Transaction.class)) {
			Transaction transaction = annotationMethod
					.getAnnotation(Transaction.class);
			JdbcHandler handler = null;
			Connection conn = null;
			try {
				String key = transaction.dataKey();
				handler = Connected.getJdbcHandler(key);
				conn = handler.getConnection();
				handler.setAutoCommit(false);
				Object obj = method.invoke(instance, args);
				if (handler.getSuccess()) {
					conn.rollback();
				} else {
					conn.commit();
				}
				return obj;
			} catch (Exception e) {
				e.printStackTrace();
				if (conn != null) {
					conn.rollback();
				}
				return null;
			} finally {
				if (conn != null) {
					conn.setAutoCommit(true);
				}
				Connected.clearThreadLocal();
			}
		} else {
			try {
				Object obj = method.invoke(instance, args);
				Connected.clearThreadLocal();
				return obj;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	public Object bind(Object instance) {
		this.instance = instance;
		return Proxy.newProxyInstance(instance.getClass().getClassLoader(),
				instance.getClass().getInterfaces(), this);
	}

}
